$('a[data-toggle="tab"]').on('show.bs.tab', function(e) {
	switch ($(e.target).text()) {
	case '预约':
		getCarNumber();
		break;
	case '预约中':
		getAppointingCarNumber();
		break;
	case '预约成功':
		getAppointSuccessCarNumber();
		break;
	case '预约失败':
		getAppointFailureCarNumber();
		break;
	default:
		break;
	}
	if ($(window).width() <= 750) {
		$('.navbar-collapse').collapse('toggle');
	}
})

$(function() {
	if ($.cookie('pId') == null) {
		window.location.replace('/schoolBus/client/cLogin');
	} else {
		getCarNumber();
	}
});

function switchStatus(i) {
	switch (i) {
	case 0:
		return '预约中、、、';
		break;
	case 1:
		return '发车中、、、';
		break;
	case 2:
		return '车次已取消！';
		break;
	case 3:
		return '车次已完成！';
		break;
	default:
		break;
	}

}

function getCarNumber() {
	$('#appoint').empty();
	$.get('/schoolBus/client/getCarNumber', function(data) {
		if (!$.isEmptyObject(data)) {
			jQuery.each(data, function(index, data) {
				var str = '<li class="list-group-item" data-toggle="modal"'
						+ 'data-target="#appointModal" data-whatever='
						+ data.dcnId + '><h4 class="list-group-item-heading">'
						+ '<label>发车时间：</label>' + data.carNumber.departureTime
						+ '</h4><div class="row">'
						+ '<div class="col-xs-12 col-sm-6">'
						+ '<label>发车地点：</label><span>'
						+ data.carNumber.departurePlace
						+ '</span></div><div class="col-xs-12 col-sm-6">'
						+ '<label>到达地点：</label><span>'
						+ data.carNumber.cnDestination
						+ '</span></div><div class="col-xs-12 col-sm-6">'
						+ '<label>预约人数：</label><span>'
						+ data.currentPassengerNumber
						+ '</span></div><div class="col-xs-12 col-sm-6">'
						+ '<label>车次状态：</label><span>'
						+ switchStatus(data.dcnStatus)
						+ '</span></div></div></li>';
				$('#appoint').append(str);
			});
			$('#appoint>li').each(function(index, li) {
				$.get('/schoolBus/client/getAppointment', {
					'pId' : $.cookie('pId'),
					'dcnId' : $(li).data('whatever')
				}, function(data) {
					if (data.flag) {
						$(li).removeAttr('data-toggle');
						$(li).removeAttr('data-target');
						$(li).css('color', 'green');
					}
				});
			});
		} else {
			$('#appoint').append(
					'<li class="list-group-item">'
							+ '<h4 class="list-group-item-heading">'
							+ '暂无信息</h4></li>');
		}
	});
}

function setTime(time) {
	if (time < 10)
		return '0' + time;
	return time;
}

function getTime(str) {
	var datetime = new Date(parseInt(str));
	var year = datetime.getFullYear();
	var month = setTime(datetime.getMonth() + 1);
	var date = setTime(datetime.getDate());
	var hour = setTime(datetime.getHours());
	var minute = setTime(datetime.getMinutes());
	var second = setTime(datetime.getSeconds());
	return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":"
			+ second;
}

function getAppointingCarNumber() {
	$('#appointing').empty();
	$.get('/schoolBus/client/getAppointmentInfo', {
		'pId' : parseInt($.cookie('pId')),
		'aStatus' : 1,
		'dcnStatus' : 0
	}, function(data) {
		if (!$.isEmptyObject(data)) {
			jQuery.each(data, function(index, data) {
				var str = '<li class="list-group-item" data-toggle="modal"'
						+ 'data-target="#appointModal" data-whatever='
						+ data.aId + '><h4 class="list-group-item-heading">'
						+ '<label>预约时间：</label>' + getTime(data.aTime)
						+ '</h4><div class="row">'
						+ '<div class="col-xs-12 col-sm-6">'
						+ '<label>发车地点：</label><span>'
						+ data.dynamicCarNumber.carNumber.departurePlace
						+ '</span></div><div class="col-xs-12 col-sm-6">'
						+ '<label>到达地点：</label><span>'
						+ data.dynamicCarNumber.carNumber.cnDestination
						+ '</span></div><div class="col-xs-12 col-sm-6">'
						+ '<label>发车时间：</label><span>'
						+ data.dynamicCarNumber.carNumber.departureTime
						+ '</span></div></div></li>';
				$('#appointing').append(str);
			});
		} else {
			$('#appointing').append(
					'<li class="list-group-item">'
							+ '<h4 class="list-group-item-heading">'
							+ '暂无信息</h4></li>');
		}
	});
}

function getAppointSuccessCarNumber() {
	$('#appointSuccess').empty();
	$.get('/schoolBus/client/getAppointmentInfo', {
		'pId' : parseInt($.cookie('pId')),
		'aStatus' : 1,
		'dcnStatus' : 3
	}, function(data) {
		if (!$.isEmptyObject(data)) {
			jQuery.each(data, function(index, data) {
				var str = '<li class="list-group-item" data-toggle="modal"'
						+ 'data-target="#appointModalDetails" data-whatever='
						+ data.dynamicCarNumber.dcnId
						+ '><h4 class="list-group-item-heading">'
						+ '<label>预约时间：</label>' + getTime(data.aTime)
						+ '</h4><div class="row">'
						+ '<div class="col-xs-12 col-sm-6">'
						+ '<label>发车地点：</label><span>'
						+ data.dynamicCarNumber.carNumber.departurePlace
						+ '</span></div><div class="col-xs-12 col-sm-6">'
						+ '<label>到达地点：</label><span>'
						+ data.dynamicCarNumber.carNumber.cnDestination
						+ '</span></div><div class="col-xs-12 col-sm-6">'
						+ '<label>发车时间：</label><span>'
						+ data.dynamicCarNumber.carNumber.departureTime
						+ '</span></div></div></li>';
				$('#appointSuccess').append(str);
			});
		} else {
			$('#appointSuccess').append(
					'<li class="list-group-item">'
							+ '<h4 class="list-group-item-heading">'
							+ '暂无信息</h4></li>');
		}
	});
}

function getAppointFailureCarNumber() {
	$('#appointFailure').empty();
	$.get('/schoolBus/client/getAppointmentInfo', {
		'pId' : parseInt($.cookie('pId')),
		'aStatus' : -1,
		'dcnStatus' : 2
	}, function(data) {
		if (!$.isEmptyObject(data)) {
			eachData('#appointFailure', data);
		}
		getAppointFailureCarNumber1();
	});
}
function getAppointFailureCarNumber1() {
	$.get('/schoolBus/client/getAppointmentInfo', {
		'pId' : parseInt($.cookie('pId')),
		'aStatus' : 0,
		'dcnStatus' : -1
	}, function(data) {
		if (!$.isEmptyObject(data)) {
			eachData('#appointFailure', data);
		}
		getAppointFailureCarNumber2();
	});
}
function getAppointFailureCarNumber2() {
	if ($('#appointFailure').find('li').length == 0) {
		$('#appointFailure').append(
				'<li class="list-group-item">'
						+ '<h4 class="list-group-item-heading">'
						+ '暂无信息</h4></li>');
	}

}

function eachData(idSelector, data) {
	jQuery.each(data, function(index, data) {
		var str = '<li class="list-group-item"' + 'data-whatever=' + data.aId
				+ '><h4 class="list-group-item-heading">'
				+ '<label>预约时间：</label>' + getTime(data.aTime)
				+ '</h4><div class="row">' + '<div class="col-xs-12 col-sm-6">'
				+ '<label>发车地点：</label><span>'
				+ data.dynamicCarNumber.carNumber.departurePlace
				+ '</span></div><div class="col-xs-12 col-sm-6">'
				+ '<label>到达地点：</label><span>'
				+ data.dynamicCarNumber.carNumber.cnDestination
				+ '</span></div><div class="col-xs-12 col-sm-6">'
				+ '<label>发车时间：</label><span>'
				+ data.dynamicCarNumber.carNumber.departureTime
				+ '</span></div></div></li>';
		$(idSelector).append(str);
	});
}

$('#appointModal').on('show.bs.modal', function(event) {
	var li = $(event.relatedTarget);
	switch (li.find('span:last').text()) {
	case '车次已取消！':
		$('#appointLabel').text('当前车次已取消，请选择其他车次！');
		$('#appointButton').css('display', 'none');
		$('#cancelAppointButton').css('display', 'none');
		break;
	case '车次已完成！':
	case '发车中、、、':
		$('#appointLabel').text('当前车次已不可预约，请选择其他车次！');
		$('#appointButton').css('display', 'none');
		$('#cancelAppointButton').css('display', 'none');
		break;
	case '预约中、、、':
		$('#appointLabel').text('确定预约当前车次？');
		$('#cancelAppointButton').css('display', 'none');
		$('#appointButton').css('display', 'inline');
		var recipient = li.data('whatever');
		var modal = $(this);
		modal.find('#passengerId').val($.cookie('pId'));
		modal.find('#dynamicCarNumberId').val(recipient);
		break;
	default:
		$('#appointLabel').text('确定取消预约当前车次？');
		$('#appointButton').css('display', 'none');
		$('#cancelAppointButton').css('display', 'inline');
		var recipient = li.data('whatever');
		var modal = $(this);
		modal.find('#dynamicCarNumberId').val(recipient);
		break;
	}
});

function appointDetails(i) {
	$.get('/schoolBus/client/getDepartureInfo', {
		'dcnId' : i
	}, function(data, textStatus) {
		var driverInfo = '<li class="list-group-item">';
		var schoolBusInfo = '<li class="list-group-item">';
		jQuery.each(data, function(index, data) {
			var str1 = '<h4 class="list-group-item-heading">'
					+ '<label>编号：</label><span>' + data.driver.dNumber
					+ '</span></h4><label>姓名：</label><span>'
					+ data.driver.dName + '</span><br/><label>联系方式：</label><span>'
					+ data.driver.dPhone + '</span>';
			var str2 = '<h4 class="list-group-item-heading">'
					+ '<label>编号：</label><span>' + data.schoolBus.sbNumber
					+ '</span></h4>' + '<label>载人数：</label><span>'
					+ data.schoolBus.passengerNumber + '</span>';
			driverInfo += str1;
			schoolBusInfo += str2;
		});
		driverInfo += '</li>';
		schoolBusInfo += '</li>';
		$('#appointModalDivDetails').append(driverInfo);
		$('#appointModalDivDetails').append(schoolBusInfo);
	});
}

$('#appointModalDetails').on('show.bs.modal', function(event) {
	$('#appointModalDivDetails').empty();
	var li = $(event.relatedTarget);
	var info = '<li class="list-group-item">' + li.html() + '</li>';
	$('#appointModalDivDetails').append(info);
	appointDetails(li.data('whatever'));
});

$('#appointButton').click(function() {
	$('#appointModal').modal('hide');
	var id = $('#dynamicCarNumberId').val();
	if (getDynamicCarNumberStatus(id)) {
		if (updateDynamicCarNumber(id, 1)) {
			$.ajax({
				type : 'post',
				url : '/schoolBus/client/addAppointmentInfo',
				data : $('#addAppointment').serialize(),
				dataType : 'json',
				success : function(data) {
					if (data.flag) {
						getCarNumber();
						$('#appointResultLabel').text('正在预约中，请稍后注意车次信息！');
					} else {
						$('#appointResultLabel').text('预约失败，请重新预约！');
					}
				}
			});
		} else {
			$('#appointResultLabel').text('网络错误，请点击左上角"校车"刷新页面！');
		}
	} else {
		$('#appointResultLabel').text('页面过期，请点击左上角"校车"刷新页面！');
	}
	$('#appointResultModal').modal('show');
});

function updateDynamicCarNumber(id, num) {
	var flag = false;
	$.ajax({
		type : 'post',
		async : false,
		url : '/schoolBus/client/updateDynamicCarNumber',
		data : {
			'dcnId' : id,
			'num' : num
		},
		success : function(data) {
			if (data.flag) {
				flag = true;
			}
		}
	});
	return flag;
}

function getDynamicCarNumberStatus(id) {
	var flag = false;
	$.ajax({
		type : 'post',
		async : false,
		url : '/schoolBus/client/getDynamicCarNumber',
		data : {
			'dcnId' : id
		},
		success : function(data) {
			if (data.flag) {
				flag = true;
			}
		}
	});
	return flag;
}

function getDynamicCarNumberId(id) {
	var flag = 0;
	$.ajax({
		type : 'post',
		async : false,
		url : '/schoolBus/client/getAppointmentDcnId',
		data : {
			'aId' : id
		},
		success : function(data) {
			flag = data;
		}
	});
	return flag;
}

$('#cancelAppointButton').click(function() {
	$('#appointModal').modal('hide');
	var id = $('#dynamicCarNumberId').val();
	var dcnId = getDynamicCarNumberId(id);
	if (getDynamicCarNumberStatus(dcnId)) {
		if (updateDynamicCarNumber(dcnId, -1)) {
			$.ajax({
				type : 'post',
				url : '/schoolBus/client/cancelAppointmentInfo',
				data : $('#addAppointment').serialize(),
				dataType : 'json',
				success : function(data) {
					if (data.flag) {
						getAppointingCarNumber();
						$('#appointResultLabel').text('取消预约成功！');
					} else {
						$('#appointResultLabel').text('取消预约失败，请重新取消！');
					}
				}
			});
		} else {
			$('#appointResultLabel').text('网络错误，请点击左上角"校车"刷新页面！');
		}
	} else {
		$('#appointResultLabel').text('页面过期，请点击左上角"校车"刷新页面！');
	}
	$('#appointResultModal').modal('show');
});